<template>
  <div class="login-container">
    <back />
    <div class="login-inner-container">
      <el-form
        ref="loginFormRef"
        :model="loginForm"
        :rules="rules"
        class="login-form"
        label-position="left"
      >
        <!-- <el-form-item prop="role">
          <div>
            <p class="select-role-text">请选择您的身份：</p>
            <el-radio-group v-model="loginForm.role">
              <el-radio v-for="item in roles" :key="item.label" :label="item.label">
                {{ item.name }}
              </el-radio>
            </el-radio-group>
          </div>
        </el-form-item> -->
        <el-form-item prop="username" label="账号：">
          <el-input ref="username" v-model="loginForm.username" placeholder="请输入账号" />
        </el-form-item>
        <el-form-item prop="password" label="密码：">
          <el-input
            ref="password"
            v-model="loginForm.password"
            type="password"
            placeholder="请输入密码"
            @keyup.enter.native="handleLogin"
          />
        </el-form-item>
        <div class="find-password">
          <span>忘记密码？<span @click="toAppeal" class="find-password-text">去找回</span></span>
        </div>
        <div class="login-form-footer">
          <el-button
            class="login-button"
            :loading="loading"
            size="large"
            type="primary"
            @click.native.prevent="handleLogin"
          >
            登录
          </el-button>
        </div>
      </el-form>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { reactive, ref } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import type { ILoginForm } from './type';
import back from '@/components/back/index.vue';
import { ElMessage, type FormInstance, type FormRules } from 'element-plus';
import { login } from '@/api/login';
import { useUserStore } from '@/store/user';
import { getUserInfo } from '@/api/system';

// 表单校验
const loginFormRef = ref<FormInstance>();
const rules = reactive<FormRules>({
  // role: [
  //   {
  //     required: true,
  //     message: '请选择您的角色',
  //     trigger: 'change',
  //   },
  // ],
  username: [
    { required: true, message: '请输入账号', trigger: 'blur' },
    { min: 1, max: 12, message: '长度为6~12位', trigger: 'blur' },
  ],
  password: [
    {
      required: true,
      message: '请输入密码',
      trigger: 'blur',
    },
  ],
});

// 登录表单
// const roles = [
//   { name: '企业人员', label: 'enterpriser' },
//   { name: '技术专家', label: 'technologist' },
//   { name: '讲师', label: 'teacher' },
// ];
const loginForm: ILoginForm = reactive({
  role: '',
  username: '',
  password: '',
});
const userStore = useUserStore();
const route = useRoute();
const router = useRouter();
const handleLogin = () => {
  submitForm(loginFormRef.value)
    .then(() => {
      login(loginForm.username, loginForm.password).then((res: any) => {
        if (res.code === 200) {
          userStore.userInfo = {
            ...userStore.userInfo,
            token: res.data.access_token,
            isLogin: true,
          };
          // 获取用户信息
          getUserInfo().then((res: any) => {
            if (res.code === 200) {
              ElMessage({
                message: '登录成功',
                type: 'success',
              });
              userStore.userInfo.userMsg = res.user;
              // 页面跳转
              const fullPath = route.query.redirect;
              console.log(fullPath);
              // 如果是从需要验证的页面跳到登录界面，则返回到原来的页面，否则返回到首页。
              if (fullPath && typeof fullPath === 'string') {
                const [path, queryString] = fullPath.split('?');
                const query: any = {};
                if (queryString) {
                  const params = new URLSearchParams(`?${queryString}`);
                  for (const [key, value] of params.entries()) {
                    query[key] = value;
                  }
                }
                router.replace({
                  path,
                  query,
                });
              } else {
                router.replace({
                  path: '/',
                });
              }
              // 登录之后刷新页面，主要是更新nav
              setTimeout(() => {
                window.location.reload();
              }, 300);
            }else{
              ElMessage({
                message: res.msg,
                type: 'error',
              });
            }
          });
        } else {
          ElMessage({
            message: res.msg,
            type: 'error',
          });
        }
      });
    })
    .catch(() => {});
};
let loading: boolean = false;
const submitForm = (formEl: FormInstance | undefined): Promise<void> => {
  return new Promise((resolve, reject) => {
    formEl?.validate((valid) => {
      if (valid) {
        resolve();
      } else {
        reject();
      }
    });
  });
};
// 找回密码
const toAppeal = () => {
  router.push({
    name: 'appeal',
  });
};
</script>

<style scoped lang="scss">
$mg-20: 20px;
.login-container {
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 10px;
  .back {
    position: absolute;
    top: 10px;
    left: 10px;
  }
  .login-inner-container {
    width: 35%;
    min-width: 350px;
    max-width: 600px;
    padding: 20px;
    background-color: #fff;
    .find-password {
      margin-bottom: $mg-20;
      &-text {
        color: #409eff;
        cursor: pointer;
        &:hover {
          text-decoration: underline;
        }
      }
    }
    .login-form-footer {
      .login-button {
        width: 100%;
      }
    }
  }
}
</style>
